package com.ruoyi.project.channel.uxInfo.service;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.channel.uxInfo.mapper.UxInfoMapper;
import com.ruoyi.project.channel.uxInfo.domain.UxInfo;
import com.ruoyi.project.channel.uxInfo.service.IUxInfoService;
import com.ruoyi.common.utils.text.Convert;

/**
 * 第三方 服务层实现
 * 
 * @author CAIN
 * @date 2020-02-23
 */
@Service
public class UxInfoServiceImpl implements IUxInfoService 
{
	@Autowired
	private UxInfoMapper uxInfoMapper;

	private static final Logger log = LoggerFactory.getLogger(UxInfoServiceImpl.class);
	/**
     * 查询第三方信息
     * 
     * @param uxId 第三方ID
     * @return 第三方信息
     */
    @Override
	public UxInfo selectUxInfoById(Long uxId)
	{
	    return uxInfoMapper.selectUxInfoById(uxId);
	}
	
	/**
     * 查询第三方列表
     * 
     * @param uxInfo 第三方信息
     * @return 第三方集合
     */
	@Override
	public List<UxInfo> selectUxInfoList(UxInfo uxInfo)
	{
	    return uxInfoMapper.selectUxInfoList(uxInfo);
	}
	
    /**
     * 新增第三方
     * 
     * @param uxInfo 第三方信息
     * @return 结果
     */
	@Override
	public int insertUxInfo(UxInfo uxInfo)
	{
	    return uxInfoMapper.insertUxInfo(uxInfo);
	}
	
	/**
     * 修改第三方
     * 
     * @param uxInfo 第三方信息
     * @return 结果
     */
	@Override
	public int updateUxInfo(UxInfo uxInfo)
	{
	    return uxInfoMapper.updateUxInfo(uxInfo);
	}

	/**
     * 删除第三方对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteUxInfoByIds(String ids)
	{
		return uxInfoMapper.deleteUxInfoByIds(Convert.toStrArray(ids));
	}

	/**
	 * 登录u享
	 * @param account
	 * @param password
	 * @return
	 */
	private UxInfo loginUX(String account,String password){
		HashMap<String,String> hashMap = new HashMap<>();
		hashMap.put("oemid","oem001");
		String body = HttpUtils.sendPost3("https://cloud.huaat.com/trade/auth/login",hashMap,"username="+account+"&password="+password);
		JSONObject jsonObject = JSONObject.parseObject(body);
		if(jsonObject.getBooleanValue("success")!= true){
			log.info("登录失败："+account+";"+body);
			return  null;
		}
		UxInfo searchUXinfo = new UxInfo();
		searchUXinfo.setAccount(account);
		List<UxInfo> uxInfos = selectUxInfoList(searchUXinfo);
		UxInfo uxInfo = new UxInfo();
		if(uxInfos.size()>0){
			uxInfo = uxInfos.get(0);
		}
		uxInfo.setAccount(account);
		JSONObject dataObj = jsonObject.getJSONObject("data");
		String token = dataObj.getString("access_token");
		Long expiresIn = dataObj.getLongValue("expires_in");
		uxInfo.setAuthToken(token);
		uxInfo.setExpiresIn(expiresIn);
		uxInfo.setCreateTime(new Date());
		if(uxInfos.size()>0){
			uxInfo = uxInfos.get(0);
			updateUxInfo(uxInfo);
		}else{
			insertUxInfo(uxInfo);
		}
		log.info("登录信息："+uxInfo);
		return uxInfo;
	}
	@Override
	public HashMap<String,String> getQrCode(String account, String password, ChannelOrder channelOrder){
//		String password =new String(Base64.getDecoder().decode(password_));
		HashMap resultMap = new HashMap();
		UxInfo searchUxInfo = new UxInfo();
		searchUxInfo.setAccount(account);
		List<UxInfo> infos = selectUxInfoList(searchUxInfo);
		String authToken = "";
		if(infos.size()==0){
			UxInfo uxInfoLogin = loginUX(account,password);
			authToken = uxInfoLogin.getAuthToken();
		}else{
			authToken = infos.get(0).getAuthToken();
		}

		// 创建订单
		HashMap<String,String> hashMap = new HashMap<>();
		hashMap.put("oemid","oem001");
		hashMap.put("Authorization","Bearer "+authToken);
		String params = "amount="+channelOrder.getAmount()+"&desc=商品&authCode=&settleMode=T0";
		String body = HttpUtils.sendPost3("https://cloud.huaat.com/trade/trade/prepay",hashMap,params);
		log.info("hashMap:"+hashMap.toString()+"params:"+params+";body:"+body);
		JSONObject jsonObject = JSONObject.parseObject(body);
		if(jsonObject.getString("__code")!=null && jsonObject.getString("__code").equals("401")){
			UxInfo uxInfoLogin = loginUX(account,password);
			authToken = uxInfoLogin.getAuthToken();
			hashMap.put("Authorization","Bearer "+authToken);
			body = HttpUtils.sendPost3("https://cloud.huaat.com/trade/trade/prepay",hashMap,params);
			log.info("再重试一次:"+hashMap.toString()+"params:"+params+";body:"+body);
			jsonObject = JSONObject.parseObject(body);
		}
		if(jsonObject.getBooleanValue("success")!= true){
			log.info("下单失败："+account+";"+body);
			resultMap.put("code","500");
			return  resultMap;
		}
		JSONObject resultObj = jsonObject.getJSONObject("data");
		String orderId = resultObj.getString("id");
		String qrBody = HttpUtils.sendGet("https://cloud.huaat.com/trade/trade/prepay/qrcode?orderId="+orderId+"&t=base64",hashMap,"");
		JSONObject qrObj = JSONObject.parseObject(qrBody);
		if(qrObj.getBooleanValue("success")!= true){
			log.info("获取二维码失败："+account+";"+body);
			resultMap.put("code","500");
			return  resultMap;
		}
		channelOrder.setDdId(Long.valueOf(orderId));
		channelOrder.setPayUrl(qrObj.getString("data"));
		resultMap.put("code","0");
		return  resultMap;
	}


}
